import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { ApplicationService } from '../../../service/application.service';
import { Farm } from '../../../entity/farm.model';
import { TagData } from '../../../entity/tag-data.model';
import { DataSourceService } from '../../../service/data-source/data-source.service';
import { Http } from '@angular/http';

@Component({
  selector: 'app-predictive-power',
  templateUrl: './predictive-power.component.html',
  styleUrls: ['./predictive-power.component.css']
})
export class PredictivePowerComponent implements OnInit {

  /**
   * 当前选中下标，默认0短期
   *
   * @memberof PredictivePowerComponent
   */
  active = 0;
  /**
   * 短期开始时间
   *
   * @memberof PredictivePowerComponent
   */
  startTime: Date;
  /**
   * 超短期开始时间
   *
   * @memberof PredictivePowerComponent
   */
  shortStartTime: Date;
  /**
   * 短期结束时间
   *
   * @memberof PredictivePowerComponent
   */
  endTime: Date;
  /**
   * 超短期结束时间
   *
   * @memberof PredictivePowerComponent
   */
  shortEndTime: Date;
  /**
   * 短期测点集合
   *
   * @type {string[]}
   * @memberof PredictivePowerComponent
   */
  codes: string[] = [];
  /**
   * 超短期测点集合
   *
   * @type {string[]}
   * @memberof PredictivePowerComponent
   */
  shortCodes: string[] = [];
  /**
   * 风场数据集合
   *
   * @type {FarmElectricity[]}
   * @memberof PredictivePowerComponent
   */
  farmElectricitys: FarmElectricity[] = [];
  /**
   * 页面表格短期数据集合
   *
   * @type {TableData}
   * @memberof PredictivePowerComponent
   */
  tableData: TableData;
  /**
   * 页面表格超短期数据集合
   *
   * @type {TableData}
   * @memberof PredictivePowerComponent
   */
  shortTableData: TableData;
  /**
   * 表格
   *
   * @type {ElementRef}
   * @memberof PredictivePowerComponent
   */
  @ViewChild('extab')
  extab: ElementRef;
  /**
   * 导出a标签
   *
   * @type {ElementRef}
   * @memberof PredictivePowerComponent
   */
  @ViewChild('ex')
  ex: ElementRef;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof PredictivePowerComponent
   */
  en: any;
  constructor(
    private application: ApplicationService,
    private dataSource: DataSourceService,
    private http: Http

  ) { }

  ngOnInit() {
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    const date = new Date(),
      Minutes = (Math.floor((date.getMinutes()) / 15)) * 15;
    this.startTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Minutes);
    this.shortStartTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Minutes);
    this.endTime = new Date(this.startTime.getTime() + 1000 * 60 * 60 * 72);
    this.shortEndTime = new Date(this.shortStartTime.getTime() + 1000 * 60 * 60 * 4);
    this.createFarms(this.application.currentUserFarms);
  }
  onClickHeader(activeNum: number) {
    if (this.active !== activeNum) {
      this.active = activeNum;
    }
  }
  /**
   * 根据时间段查询电量
   *
   * @memberof PredictivePowerComponent
   */
  onSearch(activeNum: number) {
    if (activeNum) {


      this.dataSource.history
        .getHistories(this.shortCodes, this.shortStartTime, this.shortEndTime, 900)
        .then(res => {

          if (!res || !res.length) { return false; };

          this.farmElectricitys.forEach(farmElectricity => {
            farmElectricity.shortTagDatas = res.filter(o => o.code === farmElectricity.shortTagCode);

          });
          this.getShortTableDatas();
          //console.log(this.shortTableData, this.tableData)
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      this.dataSource.history
        .getHistories(this.codes, this.startTime, this.endTime, 900)
        .then(res => {
          
      /* 
          res = [
            {
              code: 'NA.GD_NA_3_DQ001',
              value: 21,
              time: this.startTime,
            },
            {
              code: 'RP.GD_RP_3_DQ001',
              value: 41,
              time: this.startTime,
            },
            {
              code: 'LP.GD_LP_3_DQ001',
              value: 25,
              time: this.startTime,
            },
            {
              code: 'SW.GD_SW_3_DQ001',
              value: 14,
              time: this.startTime,
            },
            {
              code: 'HW.GD_HW_3_DQ001',
              value: 6,
              time: this.startTime,
            },
            {
              code: 'NS.GD_NS_3_DQ001',
              value: 7,
              time: this.startTime,
            },
            {
              code: 'NA.GD_NA_3_DQ001',
              value: 8,
              time: this.endTime,
            },
            {
              code: 'RP.GD_RP_3_DQ001',
              value: 9,
              time: this.endTime,
            },
            {
              code: 'LP.GD_LP_3_DQ001',
              value: 16,
              time: this.endTime,
            },
            {
              code: 'SW.GD_SW_3_DQ001',
              value: 21,
              time: this.endTime,
            },
            {
              code: 'HW.GD_HW_3_DQ001',
              value: 621,
              time: this.endTime,
            },
            {
              code: 'NS.GD_NS_3_DQ001',
              value: 7,
              time: this.endTime,
            },
          ]; 
      */
          if (!res || !res.length) { return false; };
          this.farmElectricitys.forEach(farmElectricity => {
            farmElectricity.tagDatas = res.filter(o => o.code === farmElectricity.tagCode);

          });
          this.getTableDatas();
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
  /**
   * 设置未来固定时间
   *
   * @param {number} activeNum
   * @memberof PredictivePowerComponent
   */
  onChoose(activeNum: number) {
    const date = new Date(),
      Minutes = (Math.floor((date.getMinutes()) / 15)) * 15;
    if (activeNum) {
      this.shortStartTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Minutes);
      this.shortEndTime = new Date(this.shortStartTime.getTime() + 1000 * 60 * 60 * 4);
    } else {
      this.startTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Minutes);
      this.endTime = new Date(this.startTime.getTime() + 1000 * 60 * 60 * 72);

    }
  }
  createFarms(farms: Farm[]) {
    const dq = this.application.tagDict['DQ001'], // 短期
      cdq = this.application.tagDict['CDQ001'], // 超短期
      th = ['时间', '公司（万kWh）'];
    farms.forEach(farm => {
      th.push(farm.farmName + '（万kWh）');
      const farmCode = farm.farmCode.replace(/_1$/, '_3'),
        dqCode = this.dataSource.buildTagCode([farmCode], dq),
        cdqCode = this.dataSource.buildTagCode([farmCode], cdq);
      this.codes.push(dqCode);
      this.shortCodes.push(cdqCode);
      const farmElectricity = {
        farmName: farm.farmName,
        tagCode: dqCode,
        shortTagCode: cdqCode,
        tagDatas: [],
        shortTagDatas: [],
      };
      this.farmElectricitys.push(farmElectricity);
    });
    this.tableData = {
      th: th,
      tr: []
    };
    this.shortTableData = {
      th: th,
      tr: []
    };
    this.onSearch(0);
    this.onSearch(1);

  }
  getTableDatas() {
    if (!this.farmElectricitys || !this.farmElectricitys.length) { return false; };
    const tagDatas = this.farmElectricitys[0].tagDatas,
      tr: TrData[] = [];

    tagDatas.forEach(tagData => {
      const trData: TrData = {
        time: tagData.time,
        total: 0,
        td: [],
      };
      this.farmElectricitys.forEach((farmElectricity, i) => {
        const index = farmElectricity.tagDatas.findIndex(o => new Date(o.time).getTime() === new Date(tagData.time).getTime());
        if (index > -1) {
          trData.td[i] = Math.round((farmElectricity.tagDatas[index].value * 0.1 * 0.25) * 100) / 100;
          trData.total += trData.td[i];
        }
      });
      tr.push(trData);
    });
    const trData: TrData = {
      desc: '总预测电量',
      total: 0,
      td: [],
    };
    tr.forEach((o) => {
      o.td.forEach((value, i) => {
        if (!trData.td[i]) {
          trData.td[i] = 0;
        }
        trData.td[i] += value;
      });
      trData.total += o.total;
    });
    tr.unshift(trData);
    this.tableData.tr = tr;
  }
  getShortTableDatas() {
    if (!this.farmElectricitys || !this.farmElectricitys.length) { return false; };
    const tagDatas = this.farmElectricitys[0].shortTagDatas,
      tr: TrData[] = [];
    tagDatas.sort((a, b) => {
      return new Date(a.time).getTime() - new Date(b.time).getTime();
    });
    tagDatas.forEach(tagData => {
      const trData: TrData = {
        time: tagData.time,
        total: 0,
        td: [],
      };

      this.farmElectricitys.forEach((farmElectricity, i) => {
        const index = farmElectricity.shortTagDatas.findIndex(o => new Date(o.time).getTime() === new Date(tagData.time).getTime());
        if (index > -1) {
          trData.td[i] = Math.round((farmElectricity.shortTagDatas[index].value * 0.1 * 0.25) * 100) / 100;
          trData.total += trData.td[i];
        }
      });
      tr.push(trData);
    });
    const trData: TrData = {
      desc: '总电量',
      total: 0,
      td: [],
    };
    tr.forEach((o) => {
      o.td.forEach((value, i) => {
        if (!trData.td[i]) {
          trData.td[i] = 0;
        }
        trData.td[i] += value;
      });
      trData.total += o.total;
    });
    tr.unshift(trData);
    this.shortTableData.tr = tr;

  }
  exportData(activeNum: number) {
    if (confirm('是否导出预测电量')) {
      // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
      const html = '<html><head><meta charset="utf-8" /></head><body>' + this.extab.nativeElement.outerHTML + '</body></html>';
      // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
      const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
      // 利用URL.createObjectURL()方法为a元素生成blob URL
      const href = URL.createObjectURL(blob);
      this.ex.nativeElement.href = href;
      // 设置文件名，目前只有Chrome和FireFox支持此属性
      if (activeNum) {
        this.ex.nativeElement.download = '超短期预测电量.xls';
      } else {
        this.ex.nativeElement.download = '短期预测电量.xls';
      }



    }



  }
}
interface FarmElectricity {
  farmName: string;
  tagCode: string;
  shortTagCode: string;
  tagDatas: TagData[];
  shortTagDatas: TagData[];
}
interface TableData {
  th: string[];
  tr: TrData[];
}
interface TrData {
  time?: Date;
  desc?: string;
  td: number[];
  total: number;
}



// WEBPACK FOOTER //
// ./src/app/module/data-analysis/predictive-power/predictive-power.component.ts